package com.itheima.web.shiro;

import com.itheima.common.utils.Encrypt;
import com.itheima.service.system.impl.UserServiceImpl;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.SimpleCredentialsMatcher;
import org.springframework.beans.factory.annotation.Autowired;

public class CustomCredentialsMatcher extends SimpleCredentialsMatcher {

    @Autowired
    private UserServiceImpl userService;

    /**密码比较
     * @param token
     * @param info
     * @return {@code true} if the provided token credentials are equal to the stored account credentials,
     *
     */
    @Override
    public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
        //提取表单中的明文邮箱和密码
        UsernamePasswordToken uToken = (UsernamePasswordToken) token;
        String email = uToken.getUsername();
        String password = new String (uToken.getPassword(),0,uToken.getPassword().length);

        //使用密码加工工具加密密码
        String md5Password = Encrypt.md5(password, email);

        //取出数据库密码
        String dbPassword = userService.findByEmail(email).getPassword().toString();
        //String dbPassword = info.getCredentials().toString();

        //放回值为false时会抛异常
        return super.equals(md5Password, dbPassword);
    }
}
